// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const TcbRouter = require('tcb-router')
const db = cloud.database()
const itemCollection = db.collection('campus-comment')
const userCollection = db.collection('student')

const MAX_LIMIT = 100
// 云函数入口函数
exports.main = async (event, context) => {
  const openid = event.userInfo.openId
  const itemId = event.itemId
  const app = new TcbRouter({
    event
  })
  app.router('detail', async (ctx, next) => {
    let commentList = (await itemCollection.where(({
      itemId,
      reportNum: db.command.lt(20)
    }))
    .orderBy('createTime', 'desc')
    .skip(event.start).limit(event.count).get()).data
    ctx.body = {
      commentList
    }
    if (event.ifItem) {
      let item = (await db.collection('campus').where({
        _id: itemId
      }).get()).data[0]
      ctx.body = {
        item,
        commentList
      }
    }
  })

  app.router('comment', async (ctx, next) => {
    let data = event.data
    if(data.ifAnonymous) {
      await db.collection('campus').doc(itemId).update({
        data: {
          anonymousList: db.command.addToSet(openid)
        }
      })
    }
    const _id = (await itemCollection.add({
      data: {
        ...data,
        createTime: db.serverDate(),
        _openid: openid
      }
    }))._id
    if (_id) {
      await db.collection('campus').doc(itemId).update({
        data: {
          commentNum: db.command.inc(1)
        }
      })
      ctx.body = {
        _id
      }
    } else {
      ctx.body = {
        _id: ''
      }
    }
  })

  app.router('delete', async (ctx, next) => {
    const res = await itemCollection.doc(itemId).remove()
    ctx.body = {
      res
    }
  })

  app.router('report', async (ctx, next) => {
    let ifReportedBefore = (await userCollection.where({
      _openid: openid,
      report: db.command.in([itemId])
    }).get()).data.length == 1

    const res = await userCollection.where({
      _openid: openid
    }).update({
      data: {
        report: db.command.addToSet(itemId)
      }
    })
    itemCollection.doc(itemId).update({
      data: {
        reportNum: db.command.inc(1)
      }
    })
    ctx.body = {
      res
    }
  })
  return app.serve()
}